package com.supereasy.kotlincor.ui.main

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.supereasy.kotlincor.http.MyUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request

class MainViewModel : ViewModel() {

    private val _userName = MutableLiveData<String>()

    val userName = _userName

    fun fetchUser() {
        viewModelScope.launch(Dispatchers.IO) {
            val result = getResult()
            _userName.postValue(result?: "")
        }
    }

    private suspend fun getResult(): String? {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(MyUrl.url)
            .build()
        val response = client.newCall(request).execute()
        return response.body?.string()
    }

}